package cn.sytton.taffecloud.common.base.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * springboot bean工厂工具类
 *
 * @author skyrock
 */
@Component
public class SpringContextUtil implements BeanFactoryPostProcessor, ApplicationContextAware {
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    public static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext paramApplicationContext)
            throws BeansException {
        if (applicationContext == null)
            applicationContext = paramApplicationContext;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringContextUtil.beanFactory = configurableListableBeanFactory;
    }

    public static boolean containsBean(String beanId) {
        return beanFactory.containsBean(beanId);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanId) {
        return (T) beanFactory.getBean(beanId);
    }

    public static <T> T getBean(Class<T> clazz) {
        return beanFactory.getBean(clazz);
    }
}
